<?php
/**
 * Created by PhpStorm.
 * User: hoter.zhang
 * Date: 2016/9/2
 * Time: 15:36
 */

namespace app\modules\admin\models;


use app\models\Config;
use yii\base\Model;

class BaseConfig extends Model
{

    protected function getConfigKeys() {
        return array_keys($this->attributes);
    }

    protected function initAllInternal(){
        $keys = $this->getConfigKeys();
        foreach ($keys as $key) {
            $this->initOneInternal($key);
        }
    }

    protected function initOneInternal($key, $defaultVal='') {
        $model = Config::findOne(['key'=>$key]);
        if ($model != null) {
            $this->$key = $model->val;
        } else {
            $model = new Config();
            $model->key = $key;
            $model->val = '';
            $model->save();
            $this->$key = $defaultVal;
        }
    }

    protected function saveAll(){
        $keys = $this->getConfigKeys();
        foreach ($keys as $key) {
            $this->saveOne($key, $this->$key);
        }
    }

    protected function saveOne($key, $val) {
        $val = $val==null ? '' : $val;
        Config::updateAll(['val'=>$val],['key'=>$key]);
    }
}